package com.isunland.managesystem.ui;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.FragmentManager;
import android.support.v7.app.ActionBar;
import android.text.Editable;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.text.style.ImageSpan;
import android.view.View;
import android.widget.EditText;
import android.widget.ListView;
import com.google.gson.Gson;
import com.isunland.managesystem.R;
import com.isunland.managesystem.adapter.LatestAnnounceMentAdapter;
import com.isunland.managesystem.base.BaseListFragment;
import com.isunland.managesystem.base.BaseVolleyActivity;
import com.isunland.managesystem.common.ApiConst;
import com.isunland.managesystem.entity.BaseParams;
import com.isunland.managesystem.entity.HintNumber;
import com.isunland.managesystem.entity.LatestAnnounceMent;
import com.isunland.managesystem.entity.LatestAnnounceMent.AnnounceMentDetail;
import com.isunland.managesystem.utils.ToastUtil;
import java.util.ArrayList;
import java.util.HashMap;

public class LatestAnnounceMentListFragment extends BaseListFragment {

  private final int REQUEST_DETAIL = 0;
  FragmentManager manager;
  private ArrayList<AnnounceMentDetail> mLatestAnnounceMent;
  private LatestAnnounceMentAdapter mLatestAnnounceMentAdapter;
  private EditText etannounceName;
  private AnnounceMentDetail announceMentDetail;

  @Override public String getUrl() {
    return ApiConst.URL_QUERY_LIST_LATEST_ANNOUNCEMENT_V290;
  }

  @Override public void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    ActionBar actionBar = mActivity.getSupportActionBar();
    if (actionBar != null) {

      actionBar.setTitle(R.string.latestAnnouncement);
    }
    manager = getFragmentManager();
  }

  @Override public void onViewCreated(View view, Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);
    View header =
        getLayoutInflater(savedInstanceState).inflate(R.layout.header_search_work_area, null,
            false);
    etannounceName = (EditText) header.findViewById(R.id.et_search_searchPersonHeader);
    ImageSpan imageHint = new ImageSpan(mActivity, R.drawable.ic_search_gray_64);
    SpannableString spannableString = new SpannableString("   搜索");
    spannableString.setSpan(imageHint, 0, 1, Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
    etannounceName.setHint(spannableString);
    etannounceName.addTextChangedListener(new MyTextWatcher());
    mListview.addHeaderView(header);
    //mListview.setDividerHeight(0);
  }

  @Override public HashMap<String, String> getparameters() {

    HashMap<String, String> announceMent = new HashMap<>();
    announceMent.put("curPage", "1");
    announceMent.put("pageSize", "10000");
    announceMent.put("ifGetReadReceipt", "T");

    return announceMent;
  }

  // 请求数据
  @Override public void resolveResponse(String param) {

    LatestAnnounceMent orginal = new Gson().fromJson(param, LatestAnnounceMent.class);
    mLatestAnnounceMent = orginal.getDataList();
    setAdapter(mLatestAnnounceMent);
  }

  @Override public void onListItemClick(ListView l, View v, int position, long id) {
    if (position < 2) return;
    announceMentDetail = mLatestAnnounceMentAdapter.getItem(position - 2);
    BaseVolleyActivity.newInstance(this, LatestAnnounceMentDetailActivity.class,
        new BaseParams<AnnounceMentDetail>().setItem(announceMentDetail), REQUEST_DETAIL);
  }

  // 判断适配器中的announcement为空的情况进行处理
  public void setAdapter(ArrayList<AnnounceMentDetail> announceMent) {
    if (announceMent == null || announceMent.size() == 0) {
      announceMent = new ArrayList<>();
    }
    mLatestAnnounceMentAdapter = new LatestAnnounceMentAdapter(mActivity, announceMent);
    setListAdapter(mLatestAnnounceMentAdapter);
    ((LatestAnnounceMentAdapter) getListAdapter()).notifyDataSetChanged();
  }

  /**
   * 标题模糊搜索
   */
  //	@Override
  //	public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
  //		inflater.inflate(R.menu.menu_contacts_search, menu);
  //		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
  //
  //			//MenuItem searchItem = menu.findItem(R.id.menu_item_search);
  //			//SearchView searchView =(SearchView) MenuItemCompat.getActionView(searchItem);
  //            SearchView  searchView= (SearchView) MenuItemCompat.getActionView(menu.findItem(R.id.menu_item_search));
  //
  //			SearchManager searchManager = (SearchManager) getActivity()
  //					.getSystemService(Context.SEARCH_SERVICE);
  //			ComponentName name = getActivity().getComponentName();
  //			SearchableInfo searchInfo = searchManager.getSearchableInfo(name);
  //            if (searchView!=null){
  //
  //			searchView.setSearchableInfo(searchInfo);
  //
  //			searchView.setOnQueryTextListener(new OnQueryTextListener() {
  //
  //				@Override
  //				public boolean onQueryTextSubmit(String query) {
  //					return true;
  //				}
  //
  //				@Override
  //				public boolean onQueryTextChange(String newText) {
  //					if(mLatestAnnounceMent==null|| mLatestAnnounceMent.size()==0){
  //						return false;
  //					}
  //					if (TextUtils.isEmpty(newText)) {
  //						setAdapter(mLatestAnnounceMent);
  //					}else{
  //						updateItems(newText);
  //					}
  //
  //					return true;
  //				}
  //			});
  //            }
  //		}
  //
  //		super.onCreateOptionsMenu(menu, inflater);
  //	}
  public void updateItems(String query) {

    // 通过标题来进行搜索
    ArrayList<AnnounceMentDetail> titleNames = new ArrayList<>();// 获取人名
    String str;
    for (int i = 0; i < mLatestAnnounceMent.size(); i++) {
      str = mLatestAnnounceMent.get(i).getTitle();
      if (null != str && str.contains(query)) {
        titleNames.add(mLatestAnnounceMent.get(i));
      }
    }

    if (titleNames.size() == 0) {
      // 弹出提示
      ToastUtil.show(R.string.nothisAnnouncement);
    }
    // 刷新列表
    setAdapter(titleNames);
    etannounceName.requestFocus();
  }

  @Override public void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (resultCode != Activity.RESULT_OK) {
      return;
    }
    if (requestCode == REQUEST_DETAIL) {
      announceMentDetail.setIsRead("T");
      ((LatestAnnounceMentAdapter) getListAdapter()).notifyDataSetChanged();
      HintNumber.newInstance(getActivity()).reduce(HintNumber.ANNOUNCEMENT);
      volleyPost();
    }
    super.onActivityResult(requestCode, resultCode, data);
  }

  /**
   * 文字监听
   */
  private class MyTextWatcher implements TextWatcher {

    MyTextWatcher() {
    }

    @Override
    public void beforeTextChanged(CharSequence charSequence, int start, int count, int after) {

    }

    @Override
    public void onTextChanged(CharSequence charSequence, int start, int before, int count) {
      if (mLatestAnnounceMent == null || mLatestAnnounceMent.size() == 0) {
        return;
      }
      String query = etannounceName.getText().toString().trim();
      if (TextUtils.isEmpty(query)) {
        setAdapter(mLatestAnnounceMent);
        etannounceName.requestFocus();
      } else {
        updateItems(query);
      }
    }

    @Override public void afterTextChanged(Editable editable) {

    }
  }
}
